
var Client = require('/db/mongoDBClient').Client;

if(true) {
	// mongolabs test
	client = new Client({
		url : "https://api.mongolab.com/api/1/",
		apikey : '5025c90be4b0e453bc4a100f'
	});
	database = "onswipe";
} else {
	//mongohq test
	client = new Client({
		url : 'https://api.mongohq.com',
		apikey : 'ssznpxl1hugdxzluo3lb'
	});
	database = "onswipe";
}


function listDatabases() {
	client.databases.all({
		success : function(success_data) {
			Ti.API.info('databases.all ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('database.all: error ' + error_data);
		}
	});
}

function listInvoices() {

	client.invoices.all({
		success : function(success_data) {
			Ti.API.info('invoices.all ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('invoices.all: error ' + error_data);
		}
	});
}

function listPlans() {
	client.plans.all({
		success : function(success_data) {
			Ti.API.info('plans.all ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('plans.all: error ' + error_data);
		}
	});
}

function listCollections() {
	client.collections.all({
		"db_name" : "onswipe",
		"success" : function(success_data) {
			Ti.API.info('collections.all ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('collections.all: error ' + error_data);
		}
	});
}

function createDatabase() {
	// "name":"my_new_db", "slug":"sandbox"
	// you MUST have a credit card on account to create database from
	// API, even if it is a free account
	client.databases.create({
		"data" : {
			"name" : 'test-db2',
			"slug" : 'sandbox',
		},
		"success" : function(success_data) {
			Ti.API.info('database.create ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('database.create: error ' + error_data);
		}
	});
}

function createCollection() {
	client.collections.create({
		"db_name" : "onswipe",
		"data" : {
			"name" : "content2"
		},
		"success" : function(success_data) {
			Ti.API.info('collections.create ' + success_data);
		},
		"error" : function(error_data) {
			Ti.API.info('collections.create: error ' + error_data);
		}
	});
}

function createDocument(db_name) {
	
	client.documents.create({
		"db_name" : db_name || "onswipe",
		"col_name" : "users",
		"data" : {
			'document' : {
				"username" : "PapaZhango",
				"usertype" : "TEACHER",
				"usertype" : "PapaZhango",
				"created_on" : new Date()
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.create ' + success_data);

			// now display all documents
			getDocuments(database);

		},
		"error" : function(error_data) {
			Ti.API.info('documents.create: error ' + error_data);
		}
	});
}

function documentsAll() {
	client.documents.all({
		"db_name" : db_name || "onswipe",
		"col_name" : "content",
		"success" : function(success_data) {
			Ti.API.info('documents.all ' + success_data);
		}
	});
}

function updateDocument() {
	
	client.documents.update({
		"db_name" : db_name || "onswipe",
		"col_name" : "content",
		"doc_id" : "4fcacbac33256c0008000005",
		"data" : {
			'document' : {
				"username" : "Updated Name " + new Date(),
				"data" : "20011",
				"timestamp": new Date()
			}
		},
		"success" : function(success_data) {
			Ti.API.info('documents.update ' + success_data);
		}
	});
}

function getDocuments(db_name) {
	client.documents.all({
		"db_name" : db_name || "onswipe",
		"col_name" : "content",
		"data" : {
		},
		"success" : function(success_data) {
			Ti.API.info('documents.find ' + success_data);

		}
	});
}


function  createUser(data) {
	client.documents.create({
		"db_name" : "onswipe",
		"col_name" : "users",
		"data" : {
			'document' : {
				"username" : data[0],
				"usertype" : data[1],
				"password" : data[2],
				"created_on" : new Date()
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.create ' + success_data);
			Titanium.App.Properties.setString("user_id", (JSON.parse(success_data))._id.$oid);
		},
		"error" : function(error_data) {
			Ti.API.info('documents.create: error ' + error_data);
			
		}
	});
}


function  createQuestion(data, count) {
	var video = '';
	if(count>3 && Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mymovie'+count+'.mov').exists())
	video =Ti.Utils.base64encode(Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mymovie'+count+'.mov').read()).toString();
	client.documents.create({
		"db_name" : "onswipe",
		"col_name" : "questions",
		"data" : {
			'document' : {
				"stem" : data[0],
				"options" : data[1],
				"created_by" : Titanium.App.Properties.getString("user_id"),
				"q_type" : data[2],
				"actual_answer" : data[3],
				"video" : video,
				"img" : data[4],
				"student_email" : data[5],
				"created_on" : new Date()
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.create ' + success_data);
			
		},
		"error" : function(error_data) {
			Ti.API.info('documents.create: error ' + error_data);
			
		}
	});
}


function  submitAnswers(data, count) {
	client.documents.create({
		"db_name" : "onswipe",
		"col_name" : "user_answers",
		"data" : {
			'document' : {
				"answer" : data[0],
				"answered_by" : Titanium.App.Properties.getString("user_id"),
				"q_id" : data[2],
				"created_on" : new Date()
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.create ' + success_data);
			
		},
		"error" : function(error_data) {
			Ti.API.info('documents.create: error ' + error_data);
			
		}
	});
}

function  searchQs() {
	var username = Titanium.App.Properties.getString("username");
	client.collections.find({
		"db_name" : "onswipe",
		"col_name" : "questions",
		"data" : {
			'document' : {
				'q':'{"student_email":"'+username+'"}'
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.find ' + success_data);
			//Insert data in DB. 
			var jsonObj = JSON.parse(success_data);
			var dbase = Titanium.Database.open('gyaan');
			var myResultSetQ = dbase.execute('SELECT max(id) as id FROM questions');
			var maxId =0;
			while (myResultSetQ.isValidRow()) {
				maxId = myResultSetQ.fieldByName('id');
				myResultSetQ.next();
			}
			maxId = maxId + 1;
			myResultSetQ.close();
			for (var i=0; i<jsonObj.length; i++){
				Ti.API.info('Stem '+jsonObj[i].stem);
				var options = jsonObj[i].options;
				options = options.toString();
				if(jsonObj[i].video!=null && jsonObj[i].video!=""){
					var video = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mymovie'+parseInt(maxId)+'.mov');
					var decoded = Ti.Utils.base64decode(jsonObj[i].video);
					video.write(decoded);
				}
				dbase.execute('INSERT INTO questions (id, title, actual_answer, type, lesson_id,q_id ) VALUES(?, ?, ?, ?, ?,?)', ''+parseInt(maxId),  ''+jsonObj[i].stem, ''+jsonObj[i].actual_answer.toString(),'Number Properties',1, ''+jsonObj[i]._id.$oid.toString());
				dbase.execute('INSERT INTO options (id, q_id, a, b, c, d, e) VALUES(?, ?, ?, ?, ?, ?, ?)', ''+parseInt(maxId),  ''+parseInt(maxId), ''+options.substring(options.indexOf('a')+2, (options.indexOf('b')-1)),''+options.substring(options.indexOf('b')+2, (options.indexOf('c')-1)),''+options.substring(options.indexOf('c')+2, (options.indexOf('d')-1)), ''+options.substring(options.indexOf('d')+2, (options.indexOf('e')-1)),''+options.substring(options.indexOf('e')+2, options.length));
				maxId = maxId + 1;
			}
			dbase.close();
			alert('You have some new questions ready under Practice tab');
		},
		"error" : function(error_data) {
			Ti.API.info('documents.find: error ' + error_data);
			
		}
	});
}


function  createAssessment(data, count) {
	var video = '';
	if(count>3 && Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mymovie'+count+'.mov').exists())
	video =Ti.Utils.base64encode(Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mymovie'+count+'.mov').read()).toString();
	client.documents.create({
		"db_name" : "onswipe",
		"col_name" : "assessments",
		"data" : {
			'document' : {
				"type" : data[0],
				"name" : data[1],
				"created_by" : Titanium.App.Properties.getString("user_id"),
				"components" : data[2],
				"created_on" : new Date()
			}
		},
		
		"success" : function(success_data) {
			Ti.API.info('documents.create ' + success_data);
			
		},
		"error" : function(error_data) {
			Ti.API.info('documents.create: error ' + error_data);
			
		}
	});
}




//createDocument(database);
//getDocuments(database);